package com.wn.inventory.handler;

import com.wn.common.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ author     ：NST
 * @ date       ：Created in 2022/10/20 11:38
 * @ description：全域异常处理类
 * @ modified By：
 * @ version:
 */
@RestControllerAdvice(basePackages = "com.wn.inventory.web")
public class GlobalExpectionHandler {
    //此异常为实体类中写入的校验规则校验出错抛出
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity MethodArgumentNotValidExceptionHander(MethodArgumentNotValidException e) {
        List<FieldError> errorList = e.getBindingResult().getFieldErrors();
        Map<String, String> map = errorList.stream()
                .collect(Collectors.toMap(filed -> filed.getField(), message -> message.getDefaultMessage()));
        return new ResponseEntity("400","数据异常",map);
//        String message = errorList.stream()
//                .map(s -> s.getDefaultMessage())
//                .collect(Collectors.joining(";"));
//        return new ResponseEntity("400","数据异常",message);
    }

    //此异常在参数列表校验简单参数校验出错时抛出
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity ConstraintViolationExceptionHander(ConstraintViolationException e) {
        Set<ConstraintViolation<?>> set = e.getConstraintViolations();
        Map<Path, String> map = set.stream()
                .collect(Collectors.toMap(filed -> filed.getPropertyPath(), message -> message.getMessage()));
        return new ResponseEntity("401","数据异常",map);
//        String message = set.stream()
//                .map(ConstraintViolation::getMessage)
//                .collect(Collectors.joining(";"));
//        return new ResponseEntity("401","数据异常",message);
    }
}
